package com.hackerrank.contests.nov13.challenges.oilwell;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Solution {
	private static class OilWell {
		int r, c;
		public OilWell(int r, int c) {
			this.r = r;
			this.c = c;
		}
		public int ACMEDistance(OilWell w) {
			return Math.max(Math.abs(r - w.r), Math.abs(c - w.c));
		}
	}
	private static int prim(int k, int l, int cost[][]) {
		if(cost.length < 2)
			return 0;
		// Let (k, l) be an edge of minimum cost in E;
		int t[][] = new int[cost.length - 1][2], mincost = cost[k][l], far[] = new int[cost.length];
		t[0][0] = k;
		t[0][1] = l;
		// Initialize near.
		for(int i = 0; i < cost.length; i++) {
			if(cost[i][l] < cost[i][k])
				far[i] = l;
			else
				far[i] = k;
		}
		far[k] = far[l] = -1;
		for(int i = 1; i < cost.length - 1; i++) {
			// Find n - 2 additional edges for t.
			// Let j be an index such that near[j] >= 0 and cost[j][near[j]] is minimum;
			int j = 0, mc = Integer.MAX_VALUE;
			for(k = 0; k < far.length; k++)
				if(far[k] >= 0 && cost[k][far[k]] < mc) {
					mc = cost[k][far[k]];
					j = k;
				}
			t[i][0] = j;
			t[i][1] = far[j];
			mincost += cost[j][far[j]];
			far[j] = -1;
			for(k = 0; k < cost.length; k++) {
				if(far[k] >= 0 && cost[k][far[k]] < cost[k][j])
					far[k] = j;
			}
		}
		return mincost;
	}
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int r = in.nextInt(), c = in.nextInt();
		List<OilWell> w = new ArrayList<OilWell>();
		for(int i = 0; i < r; i++)
			for(int j = 0; j < c; j++)
				if(in.nextInt() == 1)
					w.add(new OilWell(i, j));
		int cost[][] = new int[w.size()][], k = 0, l = 0, mincost = Integer.MAX_VALUE;
		for(int i = 0; i < w.size(); i++) {
			OilWell fw = w.get(i);
			cost[i] = new int[w.size()];
			for(int j = 0; j < i; j++) {
				OilWell sw = w.get(j);
				cost[i][j] = cost[j][i] = fw.ACMEDistance(sw);
				if(cost[i][j] < mincost) {
					mincost = cost[i][j];
					k = i;
					l = j;
				}
			}
		}
		System.out.println(prim(k, l, cost));
	}
}
